#include "mylabel.h"
#include <QPainter>
#include <iostream>
#include <QFileDialog>
#include <memory>
#include "utils.h"

MyLabel::MyLabel(QWidget *parent):QLabel (parent)
{
    this->setStyleSheet("border:2px solid red;");
    this->setAlignment(Qt::AlignLeft);
}

void MyLabel::mousePressEvent(QMouseEvent *event){
    const QPoint& pos = event->pos();
    cv::Scalar color;
    if(event->button() == Qt::LeftButton)
        color = SHADOW;
    else if(event->button() == Qt::RightButton)
        color = SHADOW_FREE;
    lineShadow.draw(pos.x(), pos.y(), color, LineShadow::ON_CLICK);
    loadImage(lineShadow.getOrigin());

    emit currentPosition(pos);
    emit sendMask(lineShadow.getMask());

}

void MyLabel::mouseMoveEvent(QMouseEvent *event){
    const QPoint& pos = event->pos();


    emit currentPosition(pos);
    cv::Scalar color;
    if(event->buttons() & Qt::LeftButton){
        color = SHADOW;
        std::cout<<"left:"<<"moving"<<pos.x()<<":"<<pos.y()<<std::endl;
    }

    else if(event->buttons() & Qt::RightButton){
          color = SHADOW_FREE;
          std::cout<<"right:"<<"moving"<<pos.x()<<":"<<pos.y()<<std::endl;;
    }


    lineShadow.draw(pos.x(), pos.y(), color, LineShadow::ON_MOVING);
    loadImage(lineShadow.getOrigin());

    emit currentPosition(pos);
    emit sendMask(lineShadow.getMask());

}

void MyLabel::mouseReleaseEvent(QMouseEvent *event){
    const QPoint& pos = event->pos();

    emit currentPosition(pos);
    cv::Scalar color;
    if(event->button() == Qt::LeftButton){
        color = SHADOW;
    }
    else if(event->button() == Qt::RightButton){
          color = SHADOW_FREE;
    }


    lineShadow.draw(pos.x(), pos.y(), color, LineShadow::ON_RELEASE);
    loadImage(lineShadow.getOrigin());

    emit currentPosition(pos);
    emit sendMask(lineShadow.getMask());
}

std::shared_ptr<QImage> MyLabel::loadImage(const cv::Mat& image)
{


    std::shared_ptr<QImage> pQimg = cvtMatToQImage(image);
    this->setPixmap(QPixmap::fromImage(*pQimg));
    //this->resize(Qtemp.size());

    return pQimg;
}

void MyLabel::saveMask()
{

    QString folder = QFileDialog::getExistingDirectory(nullptr,tr("select folder"), ".",)

    std::shared_ptr<QImage> img = cvtMatToQImage(lineShadow.getMask());
    img->save()
}
